import cv2
import numpy as np
def get_size(range):
    ww1 = int(math.sqrt((range[1][0] - range[0][0]) ** 2 + (range[1][1] - range[0][1]) ** 2))
    ww2 = int(math.sqrt((range[2][0] - range[3][0]) ** 2 + (range[2][1] - range[3][1]) ** 2))
    hh1 = int(math.sqrt((range[2][0] - range[1][0]) ** 2 + (range[2][1] - range[1][1]) ** 2))
    hh2 = int(math.sqrt((range[3][0] - range[0][0]) ** 2 + (range[3][1] - range[0][1]) ** 2))
    ww=int((ww1+ww2)/2)
    hh=int((hh1+hh2)/2)
    return (ww, hh)

def crop_image(input_path, range):
    # 按掩码进行剪裁
    src=cv2.imread(input_path)
    h,w,_ = src.shape
    # 裁剪： 根据裁剪区域points进行裁剪
    vertices = np.array(range, dtype=np.int32)
    mask = np.zeros((h, w), dtype=np.uint8)
    cv2.fillPoly(mask, [vertices], 255)
    cropped = cv2.bitwise_and(src, src, mask=mask).astype(np.uint8)
    # 假设我们想要旋转整个图像
    #获取掩码区域大小：# 找到掩码中非零像素的最小外接矩形
    dx, dy, dw, dh = cv2.boundingRect(mask)
    dst=cropped[dy:dy+dh, dx:dx+dw]
    return dst
def warp_image(input_path, range):
    # 透视变换
    src=cv2.imread(input_path)
    h,w,_ = src.shape
    # 目标图像大小
    dw, dh= get_size(range)
    pts1 = np.float32(range)
    pts2 = np.float32([[0, 0], [dw, 0], [dw, dh], [0, dh]])
    matrix = cv2.getPerspectiveTransform(pts1, pts2)
    dst = cv2.warpPerspective(src, matrix, (dw,dh))
    return dst
